<?php

class ProductController extends Controller {

    public function actionIndex() {
        $criteria = new CDbCriteria();
        $productSearch = new ProductSearch();
        $criteria->addCondition('status=1');
        $criteria->order = "created DESC";
        if (isset($_GET['ProductSearch'])) {
            $productSearch->attributes = $_GET['ProductSearch'];
            $params = array();
            if (strlen($_GET['ProductSearch']['name']) > 0) {
                $criteria->addCondition('name like :name');
                $params[':name'] = "%" . $_GET['ProductSearch']['name'] . "%";
            }
            if (strlen($_GET['ProductSearch']['code']) > 0) {
                $criteria->addCondition('code like :code');
                $params[':code'] = "%" . $_GET['ProductSearch']['code'] . "%";
            }
            if (isset($_GET['ProductSearch']['category_id']) && $_GET['ProductSearch']['category_id'] != 1) {
                $criteria->addCondition('category_id = :category_id');
                $params[':category_id'] = $_GET['ProductSearch']['category_id'];
            }
            $criteria->params = $params;
        }
        $count = Product::model()->count($criteria);
        $pages = new CPagination($count);
        $pages->pageSize = 10;
        $pages->applyLimit($criteria);
        $products = Product::model()->findAll($criteria);
        $this->render('index', array(
            'products' => $products,
            'pages' => $pages,
            'productSearch' => $productSearch,
        ));
    }

    /**
     * 
     */
    public function actionType() {
        if (isset($_POST['type'])) {
            $this->redirect(array('product/add', 'type' => $_POST['type']));
        }
        $this->render('type', array('listtype' => ProductType::model()->findAll('status = 1')));
    }

    /**
     * 
     */
    public function actionAdd($type = null) {
        $productType = $this->checktype($type);
        $model = new Product();
        if (isset($_GET['category_id'])) {
            $model->category_id = $_GET['category_id'];
        }
        if (isset($_POST['Product'])) {
            $model->attributes = $_POST['Product'];
            $model->product_type_id = $type;
            $model->created = date('Y-m-d H:i:s');
            $image = CUploadedFile::getInstance($model, 'image');
            if ($image != null) {
                $newName = time() . "." . $image->extensionName;
                $model->image = $newName;
            }
            if ($model->validate()) {
                if ($model->special > 0)
                    $model->sortprice = $model->special;
                else
                    $model->sortprice = $model->price;
                $model->save(false);
                //save image
                if ($image != null && isset($newName)) {
                    $image->saveAs(PATH_IMAGE_PRODUCT . $newName);
                }
                //save property    
                $this->saveProperty($model);
                $this->saveCategory($model);
                Yii::app()->user->setFlash('success', "Sản phẩm đã được lưu");
                $params = array('product/index');
                if (isset($_POST['create_product'])) {
                    $params = array('product/add');
                    $params['type'] = $model->product_type_id;
                    $params['category_id'] = $model->category_id;
                }
                Yii::app()->user->setFlash('success', "Sản phẩm đã được lưu");
                $this->redirect($params);
            }
        }
        $this->render('add', array('model' => $model, 'productType' => $productType));
    }

    /**
     * 
     */
    public function actionUpdate($id = null) {
        if ($id != null) {
            $model = Product::model()->findByPk($id);
            if ($model != null) {
                $productType = $model->product_type_id;
                $productType = ProductType::model()->findByPk($productType);
                $model->getAllCategoryId();
                if (isset($_POST['Product'])) {
                    $model->attributes = $_POST['Product'];
                    $model->sortprice = $model->price;
                    $image = CUploadedFile::getInstance($model, 'image');
                    if ($image != null) {
                        $newName = time() . "." . $image->extensionName;
                        $model->image = $newName;
                    }
                    if ($model->validate()) {
                        if ($model->special > 0)
                            $model->sortprice = $model->special;
                        else
                            $model->sortprice = $model->price;
                        $model->save(false);
                        if ($image != null && isset($newName)) {
                            $image->saveAs(PATH_IMAGE_PRODUCT . $newName);
                        }
                        //save property
                        $this->saveProperty($model);
                        $this->saveCategory($model);
                        $params = array('product/index');
                        if (isset($_POST['create_product'])) {
                            $params = array('product/add');
                            $params['type'] = $model->product_type_id;
                            $params['category_id'] = $model->category_id;
                        }
                        Yii::app()->user->setFlash('success', "Sản phẩm đã được lưu");
                        $this->redirect($params);
                    }
                }
            } else {
                throw new CHttpException(404, 'Sản phẩm này không dc tìm thấy.');
            }
        } else {
            throw new CHttpException(404, 'Sản phẩm này không dc tìm thấy.');
        }
        $this->render('add', array('model' => $model, 'productType' => $productType));
    }

    /**
     *
     * @param type $type 
     */
    private function checktype($type, $typeOfProduct = null) {
        $record = ProductType::model()->findByPk($type);
        if ($record != null) {
            if (($typeOfProduct != null && $typeOfProduct == $record->product_type_id) || $typeOfProduct == null) {
                return $record;
            }
        }
        $this->redirect(array('product/type'));
    }

    /**
     * 
     */
    public function actionDelete($id = null) {
        if ($id != null) {
            $model = Product::model()->findByPk($id);
            if ($model != null) {
                $model->status = STATUS_DELETE;
                if ($model->save()) {
                    Yii::app()->user->setFlash('success', "sản phẩm đã được xóa");
                } else {
                    Yii::app()->user->setFlash('success', "lỗi hệ thông");
                }
                $this->redirect(array('product/index'));
            } else {
                throw new CHttpException(404, 'Sản phẩm này không dc tìm thấy.');
            }
        } else {
            throw new CHttpException(404, 'Sản phẩm này không dc tìm thấy.');
        }
    }

    /**
     * 
     */
    protected function saveCategory($model) {
        //save category
        CategoryProduct::model()->deleteAll('product_id = ' . $model->product_id);
        $pc = new CategoryProduct();
        $pc->product_id = $model->product_id;
        $pc->category_id = $model->category_id;
        $pc->save();
        if (isset($_POST['Product']['categories']) && is_array($_POST['Product']['categories'])) {
            foreach ($_POST['Product']['categories'] as $value) {
                $pc = new CategoryProduct();
                $pc->product_id = $model->product_id;
                $pc->category_id = $value;
                $pc->save();
            }
        }
    }

    /**
     * 
     */
    protected function saveProperty($model) {
        ProductProperty::model()->deleteAll('product_id = ' . $model->product_id);
        if (isset($_POST['Product']['valueProperties'])) {
            foreach ($_POST['Product']['valueProperties'] as $property_id => $values) {
                if (is_array($values)) {
                    foreach ($values as $value) {
                        $product_property = new ProductProperty();
                        $product_property->product_id = $model->product_id;
                        $product_property->property_id = $property_id;
                        $product_property->property_value_id = $value;
                        $product_property->save();
                    }
                }
            }
        }
    }
    
    

}